<template>
  <view class="page"> 
    <view class="content">
      <view class="form-card">
        <!-- 原密码输入框 -->
        <view class="input-group">
          <text class="label">原密码</text>
          <view class="input-wrapper">
            <input 
              :password="!showPassword" 
              v-model="oldpassword" 
              placeholder="请输入原密码"
              class="input"
            />
            <uni-icons 
              class="eye-icon" 
              :type="showPassword ? 'eye' : 'eye-slash'" 
              size="20" 
              color="#999"
              @click="showPassword = !showPassword"
            />
          </view>
        </view>

        <!-- 新密码输入框 -->
        <view class="input-group">
          <text class="label">新密码</text>
          <view class="input-wrapper">
            <input 
              :password="!showPassword2" 
              v-model="newpassword" 
              placeholder="请输入新密码"
              class="input"
              @input="checkPasswordStrength"
            />
            <uni-icons 
              class="eye-icon" 
              :type="showPassword2 ? 'eye' : 'eye-slash'" 
              size="20" 
              color="#999"
              @click="showPassword2 = !showPassword2"
            />
            <uni-icons 
              v-if="isValidPassword" 
              class="check-icon" 
              type="checkmarkempty" 
              size="20" 
              color="#4CAF50"
            />
          </view>
          <!-- 密码强度指示器 -->
          <view class="password-strength">
            <text class="strength-label">密码强度:</text>
            <view class="strength-bars">
              <view 
                v-for="(level, index) in 3" 
                :key="index"
                class="strength-bar"
                :class="[
                  passwordStrength >= level ? strengthColors[passwordStrength - 1] : '',
                  passwordStrength >= level ? 'active' : ''
                ]"
              ></view>
            </view>
            <text class="strength-text" :class="strengthTextClass">
              {{ strengthLevels[passwordStrength - 1] || '弱' }}
            </text>
          </view>
        </view>

        <!-- 确认密码输入框 -->
        <view class="input-group">
          <text class="label">确认密码</text>
          <view class="input-wrapper">
            <input 
              :password="!showPassword3" 
              v-model="newpassword2" 
              placeholder="请确认新密码"
              class="input"
              @input="checkPasswordMatch"
            />
            <uni-icons 
              class="eye-icon" 
              :type="showPassword3 ? 'eye' : 'eye-slash'" 
              size="20" 
              color="#999"
              @click="showPassword3 = !showPassword3"
            />
            <uni-icons 
              v-if="passwordsMatch && newpassword2" 
              class="check-icon" 
              type="checkmarkempty" 
              size="20" 
              color="#4CAF50"
            />
          </view>
        </view>

        <text class="tips">密码要求：8-16位字符，包含数字、字母、特殊字符中的至少两种</text>
      </view>

      <button class="submit-btn" :class="{ 'btn-active': isFormValid }" @click="paschange">
        确认修改
      </button>
    </view>
  </view>
</template>

<script>
import {_modify} from '@/service/user.js'
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import {
  mapMutations
} from 'vuex';
export default {
  components: {UniIcons},
  data() {
    return {
      oldpassword: '',
      newpassword: '',
      newpassword2: '',
      showPassword: false,
      showPassword2: false,
      showPassword3: false,
      passwordStrength: 0,
      isValidPassword: false,
      passwordsMatch: false,
      strengthLevels: ['弱', '中', '强'],
      strengthColors: ['strength-weak', 'strength-medium', 'strength-strong']
    };
  },
  computed: {
    strengthTextClass() {
      return this.strengthColors[this.passwordStrength - 1]
    },
    isFormValid() {
      return this.oldpassword && this.isValidPassword && this.passwordsMatch
    }
  },
  onLoad() {
    this.phone = this.$store.state.userInfo.accountNum;
  },
  methods: {
    ...mapMutations(['logout']),
    // 验证是否为空
    validIsEmpty(str, tip) {
      if (str === '') {
        this.$api.msg(`${tip}不能为空`);
        return false;
      }
      return true;
    },
    //验证密码和确认密码是否一致
    validIsSameNew(pass1, pass2) {
      return pass1 === pass2;
    },
    //验证手机号和原密码是否输入正确
    validIsSameOld(account, pass) {
      let newdata;
      try {
        const value = uni.getStorageSync('userInfo');
        if (value) {
          newdata = value;
        }
      } catch (e) {
        console.error(e);
      }

      if (newdata.password != pass) {
        uni.showToast({
          title: '原密码输入错误，请重新输入',
          icon: 'none',
          duration: 850,
          mask: true
        })
        return false;
      }
      return true;
    },
    //验证码是否正确
    async modifyPassword() {
      let resultData;
      try {
        const userInfo = uni.getStorageSync('userInfo');
        // 使用 _modify 接口修改密码
        resultData = await _modify({
          account_user: userInfo.accountNum,
          password_user: this.newpassword
        });
        
        if (resultData.flag === true) {  // 根据接口返回修改判断条件
          try {
            // 更新本地存储中的密码
            userInfo.password = this.newpassword;
            uni.setStorageSync('userInfo', userInfo);
            return resultData;
          } catch (e) {
            console.error('更新本地存储失败:', e);
            throw new Error('更新本地存储失败');
          }
        } else {
          throw new Error(resultData.message || '密码修改失败');
        }
      } catch (error) {
        console.error('修改密码失败:', error);
        throw error;
      }
    },
    paschange() {
      // 添加密码格式验证
      const passwordRegex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
      
      if (!this.validIsEmpty(this.oldpassword, '原密码')) {
        this.$api.msg('请输入原密码！');
        return;
      }
      if (!this.validIsEmpty(this.newpassword || this.newpassword2, '新密码')) {
        this.$api.msg('请输入新密码！');
        return;
      }
      // 添加密码格式验证
      if (!passwordRegex.test(this.newpassword)) {
        this.$api.msg('密码必须是8-16位数字和字母的组合！');
        return;
      }
      if (!this.validIsSameNew(this.newpassword, this.newpassword2)) {
        this.$api.msg('两次密码输入不一致，请重新输入！');
        return;
      }

      // 验证原密码是否正确
      if (this.validIsSameOld(null, this.oldpassword)) {
        this.modifyPassword()
          .then(() => {
            uni.showToast({
              title: '密码修改成功！请重新登录',
              icon: 'none',
              duration: 1500
            });
            setTimeout(() => {
              this.toLogout();
            }, 1500);
          })
          .catch(error => {
            uni.showToast({
              title: error.message || '密码修改失败',
              icon: 'none'
            });
          });
      }
    },
    toLogout() {
      // 先清除本地存储
      uni.clearStorageSync();
      // 执行登出操作
      this.logout();
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/login'
      });
    },
    checkPasswordStrength() {
      const password = this.newpassword
      let strength = 0
      
      // 检查长度
      if (password.length >= 8 && password.length <= 16) {
        // 检查包含数字
        if (/\d/.test(password)) strength++
        // 检查包含字母
        if (/[a-zA-Z]/.test(password)) strength++
        // 检查包含特殊字符
        if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++
      }

      this.passwordStrength = strength
      this.isValidPassword = strength >= 2
    },
    
    checkPasswordMatch() {
      this.passwordsMatch = this.newpassword === this.newpassword2 && this.newpassword2 !== ''
    }
  },
};
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f7f7f7;
}

.header {
  background: linear-gradient(180deg, #138f87 0%, #44cdbd 100%);
  padding: 88rpx 32rpx 32rpx;
  
  .header-title {
    color: #fff;
    font-size: 36rpx;
    font-weight: 500;
  }
}

.content {
  margin-top: -20rpx;
  padding: 32rpx;
}

.form-card {
  margin-top: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
}

.input-group {
  margin-bottom: 32rpx;

  .label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
    display: block;
  }
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 0 24rpx;
  
  .input {
    flex: 1;
    height: 88rpx;
    font-size: 28rpx;
    color: #333;
  }

  .eye-icon, .check-icon {
    padding: 20rpx;
  }
}

.password-strength {
  margin-top: 16rpx;
  display: flex;
  align-items: center;
  
  .strength-label {
    font-size: 24rpx;
    color: #666;
    margin-right: 16rpx;
  }

  .strength-bars {
    display: flex;
    gap: 8rpx;
    
    .strength-bar {
      width: 60rpx;
      height: 8rpx;
      background: #eee;
      border-radius: 4rpx;
      transition: all 0.3s;
      
      &.active {
        &.strength-weak { background: #ff4d4f; }
        &.strength-medium { background: #faad14; }
        &.strength-strong { background: #52c41a; }
      }
    }
  }

  .strength-text {
    margin-left: 16rpx;
    font-size: 24rpx;
    
    &.strength-weak { color: #ff4d4f; }
    &.strength-medium { color: #faad14; }
    &.strength-strong { color: #52c41a; }
  }
}

.tips {
  font-size: 24rpx;
  color: #999;
  margin-top: 32rpx;
  display: block;
}

.submit-btn {
  margin-top: 48rpx;
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #138f87;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  opacity: 0.7;
  transition: all 0.3s;

  &.btn-active {
    opacity: 1;
    
    &:active {
      transform: scale(0.98);
      background: #44cdbd;
    }
  }
}
</style>